<?php

header( 'Content-Type: text/plain' );

set_time_limit( 0 );
session_start();

if ( empty( $_GET['room'] ) || !trim( $_GET['room'] ) )
	$_GET['room'] = 'public';

$_GET['room'] = preg_replace( '/[^a-z0-9_\-]/', '', strtolower( trim( $_GET['room'] ) ) );

if ( !file_exists( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' ) )
	touch( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' );

$size = filesize( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' );

$online = (array)file( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' );

foreach ( $online as $id => $on ) {
	if ( (int)substr( $on, 32 ) < time() - 75 )
		unset( $online[$id] );
	if ( substr( $on, 0, 32 ) == md5( $_SERVER['HTTP_USER_AGENT'] . '@' . $_SERVER['REMOTE_ADDR'] ) )
		unset( $online[$id] );
}

$online[] = md5( $_SERVER['HTTP_USER_AGENT'] . '@' . $_SERVER['REMOTE_ADDR'] ) . time() . ':' . urlencode( $_SESSION['name'] );
session_write_close(); // Speed things up, let other scripts use sessions for the same user.

sort( $online );
file_put_contents( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt', implode( "\n", array_map( 'trim', $online ) ) );

$i = $_GET['immediate'] ? -1 : 2500;
while ( $i-- > 0 && filesize( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' ) == $size ) {
	clearstatcache();
	usleep( 10000 );
}

readfile( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' );

?>